# coding=utf-8
# from __future__ import unicode_literals  # buddy
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, FileResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from ha.models import *
from django.db.models import Q, Count, Sum
from django.apps import apps
from django.contrib.auth.models import User
from django.utils.http import urlquote
import json
import collections
import datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core import serializers
import docx
import math


# Create your views here.

def index(req):
    total_record = 0
    for model in apps.all_models["ha"].values():
        total_record = total_record + model.objects.count()

    biaozhun_total = Nanyabiaozhun.objects.count()

    return render(req, 'back/index.html',{"biaozhun_total": biaozhun_total})


def index_front(req):
    data = dict()

    # buddy
    total_record = 0
    for model in apps.all_models["ha"].values():
        total_record = total_record + model.objects.count()

    # data['contents'] = Neirong.objects.filter(firstleibie='BZGG').order_by('-addTime')[:8]
    data['contents'] = Neirong.objects.filter(firstleibie='BZXW').order_by('-addTime')[:8]

    data['contents1'] = Neirong.objects.filter(firstleibie='BZGG').order_by('-addTime')[:8]

    data['contents2'] = Neirong.objects.filter(firstleibie='ZCFG').order_by('-addTime')[:8]

    data['contents3'] = Neirong.objects.filter(firstleibie='WTOTB').order_by('-addTime')[:8]

    return render(req, 'front/index.html', data)


# buddy

def get_left(current_page, left, num_pages):
    """
    辅助函数，获取当前页码的值得左边两个页码值，
    要注意一些细节，比如不够两个那么最左取到2，为了方便处理，包含当前页码值，
    比如当前页码值为5，那么pages = [3,4,5]
    """
    if current_page == 1:
        return []
    elif current_page == num_pages:
        l = [i - 1 for i in range(current_page, current_page - left, -1)
             if i - 1 > 1]
        l.sort()
        return l
    l = [i for i in range(current_page, current_page - left, -1)
         if i > 1]
    l.sort()
    return l


def get_right(current_page, right, num_pages):
    """
    辅助函数，获取当前页码的值得右边两个页码值，要注意一些细节，比如不够两个那么最右取到最大页码值。
    不包含当前页码值。比如当前页码值为5，那么pages = [6,7]
    """
    if current_page == num_pages:
        return []
    return [i + 1 for i in range(current_page, current_page + right - 1)
            if i < num_pages - 1]


def pagePaginator(contentlist, page, totalnumber):
    left = 3  # 当前页码左边显示几个页码号 -1，比如3就显示2个
    right = 3
    number_pages = math.ceil(totalnumber / 10)
    if number_pages == 0:
        number_pages = 1
    try:
        pages = get_left(page, left, number_pages) \
                + get_right(page, right, number_pages)
        # 调用了两个辅助函数，根据当前页得到了左右的页码号
    except PageNotAnInteger:
        pages = get_right(page, right, number_pages)
    except EmptyPage:
        pages = get_left(page, left, number_pages)
    has_previous = 0
    previous_page_number = page - 1
    if page > 1:
        has_previous = 1
    has_next = 0
    next_page_number = page + 1
    if page < number_pages:
        has_next = 1

    data = {}
    data['contentPage'] = contentlist  # 当前内容页
    data['contentPage_num'] = page
    data['has_previous'] = has_previous
    data['previous_page_number'] = previous_page_number
    data['has_next'] = has_next
    data['next_page_number'] = next_page_number
    data['number'] = totalnumber
    data['pages'] = pages
    data['first_page'] = 1
    data['last_page'] = number_pages

    try:
        # 获取 pages 列表第一个值和最后一个值，主要用于在是否该插入省略号的判断，在模板文件中将会体会到它的用处。
        # 注意这里可能产生异常，因为pages可能是一个空列表，比如本身只有一个分页，那么pages就为空，因为我们永远不会获取页码为1的页码号（至少有1页，1的页码号已经固定写在模板文件中）
        data['pages_first'] = pages[0]
        data['pages_last'] = pages[-1] + 1
        # +1的原因是为了方便判断
    except IndexError:
        data['pages_first'] = 1  # 发生异常说明只有1页
        data['pages_last'] = 2
    return data


def information_service(req):
    data = dict()
    code = req.GET.get('data')
    page = req.GET.get('page')
    data['code'] = code
    if page is None:
        page = 1
    page = int(page)
    Pstart = page * 10 - 10
    Pend = page * 10
    if code == 'detail':
        id = req.GET.get('id')
        data['content'] = Neirong.objects.get(id=id)
        return render(req, 'front/information_service_detail.html', data)
    elif code == 'BZXW':
        article = Neirong.objects.filter(firstleibie='BZXW').order_by('-addTime')[Pstart:Pend]
        totalnumber = Neirong.objects.filter(firstleibie='BZXW').count()
        page_data = pagePaginator(article, page, totalnumber)
        data = dict(data, **page_data) # 合并两个dict
        return render(req, 'front/biaozhunxinwen.html', data)
    elif code == 'BZGG':
        article = Neirong.objects.filter(firstleibie='BZGG').order_by('-addTime')[Pstart:Pend]
        totalnumber = Neirong.objects.filter(firstleibie='BZGG').count()
        page_data = pagePaginator(article, page, totalnumber)
        data = dict(data, **page_data)  # 合并两个dict
        return render(req, 'front/biaozhungonggao.html', data)
    elif code == 'ZCFG':
        article = Neirong.objects.filter(firstleibie='ZCFG').order_by('-addTime')[Pstart:Pend]
        totalnumber = Neirong.objects.filter(firstleibie='ZCFG').count()
        page_data = pagePaginator(article, page, totalnumber)
        data = dict(data, **page_data)  # 合并两个dict
        return render(req, 'front/zhengcefagui.html', data)
    elif code == 'WTOTB':
        article = Neirong.objects.filter(firstleibie='WTOTB').order_by('-addTime')[Pstart:Pend]
        totalnumber = Neirong.objects.filter(firstleibie='WTOTB').count()
        page_data = pagePaginator(article, page, totalnumber)
        data = dict(data, **page_data)  # 合并两个dict
        return render(req, 'front/WTOtongbao.html', data)
    else:
        return HttpResponseRedirect('/index_front/')


# 前台信息搜索
def quality_search(req):
    if req.method == 'GET':
        return render(req, 'front/quality_search.html', {})


#前台高级搜索
def quality_advancedsearch(req):

    biaozhunhao = req.POST.get('biaozhunhao')
    biaozhunbianhao = req.POST.get('biaozhunbianhao')
    ebiaozhunmingcheng = req.POST.get('ebiaozhunmingcheng')
    cbiaozhunmingcheng = req.POST.get('cbiaozhunmingcheng')

    searchList = []
    if biaozhunhao:
        q_biaozhunhao = Q(standardcode__contains=biaozhunhao)
        searchList.append(q_biaozhunhao)
    if biaozhunbianhao:
        q_biaozhunbianhao = Q(standard__contains=biaozhunbianhao)
        searchList.append(q_biaozhunbianhao)
    if ebiaozhunmingcheng:
        q_ebiaozhunmingcheng=Q(title1__contains=ebiaozhunmingcheng)
        searchList.append(q_ebiaozhunmingcheng)
    if cbiaozhunmingcheng:
        q_cbiaozhunmingcheng=Q(title2__contains=cbiaozhunmingcheng)
        searchList.append(q_cbiaozhunmingcheng)
    condition = Q()
    for constraint in searchList:
        condition = condition & constraint
    products = Nanyabiaozhun.objects.filter(condition)[:500]
    data = {}
    data['products'] = products

    data['query'] = json.dumps(biaozhunhao)
    data['query1'] = json.dumps(biaozhunbianhao)
    data['query2'] = json.dumps(ebiaozhunmingcheng)
    data['query3'] = json.dumps(cbiaozhunmingcheng)
    return render(req, 'front/quality_search.html', data)


@csrf_exempt
def Content_list(req):
    if req.method == 'GET':
        data = req.GET.get('data')
        if data == 'BZXW':
            content = Neirong.objects.filter(firstleibie='BZXW')
            firstleibie = 'BZXW'
            return render(req, 'back/Content_list.html', {'content': content, 'firstleibie': firstleibie})
        elif data == 'BZGG':
            content = Neirong.objects.filter(firstleibie='BZGG')
            firstleibie = 'BZGG'
            return render(req, 'back/Content_list.html', {'content': content, 'firstleibie': firstleibie})
        elif data == 'ZCFG':
            content = Neirong.objects.filter(firstleibie='ZCFG')
            firstleibie = 'ZCFG'
            return render(req, 'back/Content_list.html', {'content': content, 'firstleibie': firstleibie})
        elif data == 'WTOTB':
            content = Neirong.objects.filter(firstleibie='WTOTB')
            firstleibie = 'WTOTB'
            return render(req, 'back/Content_list.html', {'content': content, 'firstleibie': firstleibie})
        elif data == 'detail':
            id = req.GET.get('id')
            firstleibie = req.GET.get('firstleibie')
            content = Neirong.objects.get(id=id)
            return render(req, 'back/Content_detail.html', {'content': content, 'firstleibie': firstleibie})


@csrf_exempt
def Content_add(req):
    if req.method == 'GET':
        data = req.GET.get('data')
        if data == 'BZXW':
            firstleibie = 'BZXW'
        elif data == 'BZGG':
            firstleibie = 'BZGG'
        elif data == 'ZCFG':
            firstleibie = 'ZCFG'
        elif data == 'WTOTB':
            firstleibie = 'WTOTB'
        return render(req, 'back/Content_add.html', {'firstleibie': firstleibie})
    else:
        data = req.POST.get('data')
        if data == 'addcontent':
            firstleibie = req.POST.get('firstleibie')
            title = req.POST.get('title')
            context = req.POST.get('context')
            Neirong.objects.create(title=title, firstleibie=firstleibie,
                                    context=context)
            return HttpResponseRedirect('/Content_list/?data=' + firstleibie)
        elif data == 'del':
            id = req.POST.get('id')
            Neirong.objects.filter(id=id).delete()
            result = "success"
            return HttpResponse(json.dumps(result), content_type='application/json')


@csrf_exempt
def login(req):
    if req.method == 'GET':
        return render(req, 'back/login.html', {})
    else:
        username = req.POST.get('username')
        password = req.POST.get('password')
        data = dict()
        x = User.objects.filter(username=username, password=password).all()
        if len(x) > 0:
            data['result'] = 'success'
        else:
            data['result'] = ''
            data['errors'] = '用户名或密码错误'
        return HttpResponse(json.dumps(data), content_type='application/json')


def Fenxibaogao_page(req):
    return render(req, "back/Fenxibaogao.html", {})


def create_analysis(req):
    try:
        biaozhunhao = req.GET.get('biaozhunhao')
        file = open("media/upload/files/" + biaozhunhao +".pdf", "rb")
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="%s"' % (urlquote(biaozhunhao+".pdf"))
        return response
    except:
        return HttpResponse("Sorry but Not Found the File")


def download(req):
    try:
        biaozhunhaojiequ = req.GET.get('str2')
        file = open("media/upload/files/" + biaozhunhaojiequ +".pdf", "rb")
        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="%s"' % (urlquote(biaozhunhaojiequ+".pdf"))
        return response
    except:
        return HttpResponse("Sorry but Not Found the File")


def get_data_by_ajax(req):
    if req.is_ajax():
        req_type = req.GET.get("type")


def danweijianjie(req):
    return render(req, "front/danweijianjie.html")


def jibengaikuang(req):
    return render(req, "front/jibengaikuang.html")


def lianxiwomen(req):
    return render(req, "front/lianxiwomen.html")


def biaozhunxiazai(req):
    return render(req, "front/biaozhunxiazai.html")


def toubusousuo(req):

    guanjianzi = req.POST.get('guanjianzi')
    searchList = []
    q_guanjianzi = Q(context__contains=guanjianzi)
    searchList.append(q_guanjianzi)

    condition = Q()
    for constraint in searchList:
        condition = condition & constraint
        record = Neirong.objects.filter(condition)
        data = {}
        data['record'] = record
        return render(req, 'front/toubuxinwen.html', data)

def shujutongji(req):
    return render(req, 'front/quality_data.html')


def shujutongji(req):

    biaozhun_total = Nanyabiaozhun.objects.count()

    return render(req, 'front/shujutongji.html', {"biaozhun_total": biaozhun_total})
